package com.example.day6_viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.RadioGroup;

import com.example.day6_viewpager.adapter.MyPagerAdapter;
import com.example.day6_viewpager.fragment.WelcomeFragmentOne;
import com.example.day6_viewpager.fragment.WelcomeFragmentThree;
import com.example.day6_viewpager.fragment.WelcomeFragmentTwo;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

//欢迎页面
public class WelcomeActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private RadioGroup radioGroup;
    private List<Fragment> list;
    private MyPagerAdapter myPagerAdapter;
    private Timer timer;
    private int position= 0;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(position++);
            if(position == 3){
                timer.cancel();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        initPager();
        initTimer();
        initListsener();
    }
    private void initListsener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        radioGroup.check(R.id.rb1);
                        break;
                    case 1:
                        radioGroup.check(R.id.rb2);
                        break;
                    case 2:
                        radioGroup.check(R.id.rb3);
                        break;
                }

            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
    private void initTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(101);
            }
        },1000,1000);
    }
    private void initPager() {
        radioGroup = findViewById(R.id.group);
        viewPager = findViewById(R.id.view_pager);
        list = new ArrayList<>();
        list.add(new WelcomeFragmentOne());
        list.add(new WelcomeFragmentTwo());
        list.add(new WelcomeFragmentThree());
        myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(),list);
        viewPager.setAdapter(myPagerAdapter);

    }
}
